package com.hnhd.eorder.db;

import java.util.ArrayList;

import android.content.ContentValues;
import android.database.Cursor;

import com.hnhd.eorder.vo.Type;

/**
 * 菜品类型数据操作类
 * 
 * @author peng
 * 
 */
public class TypeUtil {
	
	
	public static Type getTypeByName(String typeName) {
		Cursor cursor = SQLUtil.query(SQLUtil.TYPE, null, "name=?",
				new String[] { typeName }, null, null, null);
		Type type = null;
		if (cursor.moveToFirst()) {
			do {
				type = new Type();
				type.setTypeId(cursor.getInt(0));
				type.setTypeName(cursor.getString(1));
			} while (cursor.moveToNext());
		}
		if (cursor != null && !cursor.isClosed()) {
			cursor.close();
		}
		return type;
	}

	public static Type getTypeById(String id) {
		Cursor cursor = SQLUtil.query(SQLUtil.TYPE, null, "id=?",
				new String[] { id }, null, null, null);
		Type type = null;
		if (cursor.moveToFirst()) {
			do {
				type = new Type();
				type.setTypeId(cursor.getInt(0));
				type.setTypeName(cursor.getString(1));
			} while (cursor.moveToNext());
		}
		if (cursor != null && !cursor.isClosed()) {
			cursor.close();
		}
		return type;
	}

	public static ArrayList<Type> getAllTypes() {
		Cursor cursor = SQLUtil.getReadableDatabase().rawQuery(
				"SELECT * FROM " + SQLUtil.TYPE, null);
		ArrayList<Type> types = new ArrayList<Type>();
		if (cursor.moveToFirst()) {
			do {
				Type type = new Type();
				type.setTypeId(cursor.getInt(0));
				type.setTypeName(cursor.getString(1));
				types.add(type);
			} while (cursor.moveToNext());
		}
		if (cursor != null && !cursor.isClosed()) {
			cursor.close();
		}
		return types;
	}

	public static long insertType(Type type) {
		ContentValues values = new ContentValues();
		values.put("id", type.getTypeId());
		values.put("name", type.getTypeName());
		return SQLUtil.getWritableDatabase().insert(SQLUtil.TYPE, null,
				values);
	}

	public static long updateType(Type type) {
		ContentValues values = new ContentValues();
		values.put("id", type.getTypeId());
		values.put("name", type.getTypeName());
		return SQLUtil.getWritableDatabase().update(SQLUtil.TYPE, values,
				"id=?", new String[] { String.valueOf(type.getTypeId()) });
	}

	public static void deleteType(Type type) {
		SQLUtil.getWritableDatabase().delete(SQLUtil.TYPE, "id=?",
				new String[] { String.valueOf(type.getTypeId()) });
	}
	

	public static void deleteAllTypes() {
		SQLUtil.getWritableDatabase().delete(SQLUtil.TYPE, null,null);
	}
}
